package cn.hinglo.gameclaw.admin.service;

import cn.hinglo.gameclaw.admin.dao.ArticleDao;
import cn.hinglo.gameclaw.data.entity.Result;
import cn.hinglo.gameclaw.data.utils.*;
import cn.hinglo.gameclaw.user.bean.Article;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @createTime: 2018/7/14
 * @author: HingLo
 * @description:
 */
@Service
public class ArticleService {
    private final ArticleDao articleDao;

    @Autowired
    public ArticleService(ArticleDao articleDao) {
        this.articleDao = articleDao;
    }

    /***
     * 添加文章内容
     * @param article 文章实体
     * @param img 文章图片
     * @return 添加结果
     */
    public Result addService(Article article, MultipartFile img) {
        String fileName = FileImageUtils.createFileNameUtils(img);
        article.setStatus(false);
        article.setImage(fileName);
        // 设置时间
        if (article.getType() == 0) {
            article.setStartDate(new Date());
        }

        if (FileImageUtils.saveImageUtils(img, fileName, FieldUtils.IMAGE_9)) {
            return articleDao.insert(article) == 1 ? ResultUtils.success() : ResultUtils.error("添加失败");
        }
        return ResultUtils.error("图片上传失败");
    }

    /**
     * 文章列表
     *
     * @param type     文章类型
     * @param page     页码
     * @param pageSize 页码大小
     * @return 返回结果
     */
    public Result listService(Integer type, int page, int pageSize) {
        String key = "" + type + page + pageSize;
        Map<String, Object> map = EhcacheUtil.get("articleList", key);
        if (map != null) {
            ResultUtils.success(map);
        }
        if (pageSize < 1) {
            pageSize = 10;
        }
        if (page < 1) {
            page = 1;
        }

        Page pages = PageHelper.startPage(page, pageSize).setOrderBy("start_date desc");

        List<Article> list;
        if (type == null || type == -1) {
            list = articleDao.selectAll();
        } else {
            Article article = new Article().setType(type);
            list = articleDao.select(article);
        }
        list.forEach(x -> x.setImage(CommonUtils.imgInstall(x.getImage(), FieldUtils.IMAGE_9)));
        map = new HashMap<>(2);
        map.put("result", list);
        map.put("total", pages.getTotal());
        EhcacheUtil.put("articleList", key, map);
        return ResultUtils.success(map);
    }

    /**
     * 修改文章内容
     *
     * @param article 新内容实体
     * @param img     图片
     * @return 返回结果
     */
    public Result updateService(Article article, MultipartFile img) {

        // 如果有图片就更新图片
        if (img != null) {
            String fileName = FileImageUtils.createFileNameUtils(img);
            article.setImage(fileName);
            if (!FileImageUtils.saveImageUtils(img, fileName, FieldUtils.IMAGE_9)) {
                return ResultUtils.error("图片保存失败");
            }
        }
        return articleDao.updateByPrimaryKeySelective(article) == 1 ? ResultUtils.success() : ResultUtils.error("修改失败");

    }

    /**
     * 通过文章的ID删除文章
     *
     * @param id 文章ID
     * @return 删除结果
     */
    public Result deleteService(Long id) {
        return articleDao.deleteByPrimaryKey(id) == 1 ? ResultUtils.success() : ResultUtils.error("删除失败");
    }

    /**
     * 修改文章状态
     *
     * @param id     文章ID
     * @param status 状态
     * @return 返回结果
     */
    public Result releaseService(Long id, boolean status) {
        Article article = new Article().setId(id).setStatus(status);
        return articleDao.updateByPrimaryKeySelective(article) == 1 ? ResultUtils.success() : ResultUtils.error("修改失败");
    }

    /**
     * 通过文章的ID 来查看文章的具体内容
     *
     * @param id 文章的ID
     * @return 文章的具体的内容
     */
    public Result indexService(Long id) {
        String body = EhcacheUtil.get("article", id);
        if (StrUtil.isNotBlank(body)) {
            return ResultUtils.success(body);
        }

        Article article = articleDao.selectByPrimaryKey(id);
        if (article == null) {
            return ResultUtils.error("该文章不存在");
        }
        String url = article.getUrl();

        HttpRequest httpRequest = HttpRequest.get(url);
        HttpResponse httpResponse = httpRequest.execute();
        body = html(httpResponse.body());
        if (StrUtil.isNotBlank(body)) {
            EhcacheUtil.put("article", id, body);
        }

        return ResultUtils.success(body);
    }

    /**
     * 解析响应的HTML,并替换文章中的图片url
     *
     * @param body 内容
     * @return 返回替换了image标签的文章内容
     */
    private String html(String body) {
        String img = "data-src";
        Document document = Jsoup.parse(body, "utf-8");
        document.body().select("img[data-src]").forEach(x -> {
            String fileName = IdUtils.getId() + ".png";
            if (download(x.attr(img), fileName)) {
                x.attr("src", CommonUtils.imgInstall(fileName, FieldUtils.IMAGE_9));
                x.removeAttr("data-src");
            }

        });
        return document.toString();
    }

    /**
     * 下载指定的图片
     *
     * @param url      图片url
     * @param fileName 文件名称
     * @return 下载结果
     */
    private boolean download(String url, String fileName) {
        HttpRequest httpRequest = HttpRequest.get(url);
        HttpResponse httpResponse = httpRequest.execute();
        byte[] img = httpResponse.bodyBytes();
        if (img == null) {
            return false;
        }
        return FileImageUtils.saveImageUtils(img, fileName, FieldUtils.IMAGE_9);
    }
}